package com.android.activity;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.controler.RemoteControlReceiver;

public class Receiver extends Activity {

    private ImageView imgView;
	private Gallery g = null;
	private static final int REQUEST_ENABLE_BT = 1;
	public static final int MESSAGE_READ = 2;
	private BluetoothAdapter mAdapter = null;
	private BluetoothServerSocket mmServerSocket = null;
	private static final UUID MY_UUID = UUID
			.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
	private static final String NAME = "Receiver";
	private static final String TAG = "Receiver";
	private static final boolean D = true;
	private InputStream mmInStream;
	private HiloEscuchador mT;
	private int estado = 1;
	private int posicionImagen = 0;
	private int numeroImagenesTotales = 0;
	private RemoteControlReceiver mReceiverService = null;
	private int imagenSeleccionada = 0;
	String[] mFiles = null;
	private Uri[] mUrls;
	private boolean PARAR_GALERIA = false;

	/** Called when the activity is first created. */
	@Override
	public synchronized void onCreate(Bundle savedInstanceState) {
		if (D)
			Log.e(TAG, "++ ON create ++");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.visor);
		if (comprobarSD()) {
			File ReceiverVisor = Environment.getExternalStorageDirectory();
			Log.e(TAG, "++ getDataDirectory ++");
			File[] imagelist = ReceiverVisor.listFiles(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return ((name.endsWith(".jpg")) || (name.endsWith(".png")));
				}
			});
			if (imagelist != null) {
				Log.e(TAG, "++ imagelistnotnull ++");
				mFiles = new String[imagelist.length];

				for (int i = 0; i < imagelist.length; i++) {
					mFiles[i] = imagelist[i].getAbsolutePath();
				}
				mUrls = new Uri[mFiles.length];

				for (int i = 0; i < mFiles.length; i++) {
					mUrls[i] = Uri.parse(mFiles[i]);
				}
				// ImageView
				imgView = (ImageView)findViewById(R.id.imageView01);	

				
				
				// Se carga la galer�a con todas las im�genes.
				Log.e(TAG, "++ findViewById ++");
				g = (Gallery) findViewById(R.id.gallery);
				Log.e(TAG, "++ setAdapter ++");
				g.setAdapter(new ImageAdapter(this));

				if (D)
					Log.e(TAG, "Cuantas im�genes hay en el galery = "
							+ g.getCount());
				numeroImagenesTotales = g.getCount();

				// Al iniciar la actividad se muestra la primera imagen.
				Log.e(TAG, "++ imagenSeleccionada ++");
				g.setSelection(imagenSeleccionada);
		        imgView.setImageResource(imagenSeleccionada);
				Log.e(TAG, "++ setFadingEdgeLength ++");
				g.setFadingEdgeLength(40);

				mAdapter = BluetoothAdapter.getDefaultAdapter();
				if (D)
					Log.e(TAG, "++ mAdapter creado ++");
				
				if (null != mAdapter) {
					if (!mAdapter.isEnabled()) {
						if (D)
							Log.e(TAG, "madapter no activado");
						Intent enableIntent = new Intent(
								BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
					} else {
						if (D)
							Log.e(TAG, "antes de arrancar el hilo");
						mT = new HiloEscuchador();
						mT.start();
						if (D)
							Log.e(TAG, "hilo arrancado");
					}
				} else {
					Toast.makeText(Receiver.this, getResources().getString(R.string.nobluetooth),
									Toast.LENGTH_SHORT).show();					
				}
			} else {
				Toast.makeText(Receiver.this, getResources().getString(R.string.noimages),
								Toast.LENGTH_SHORT).show();
				super.finish();
			}
		} else {
			Toast.makeText(Receiver.this, getResources().getString(R.string.noSD),
							Toast.LENGTH_SHORT).show();
			super.finish();
		}

	}

	@Override
	public void onStart() {
		super.onStart();

		if (D)
			Log.e(TAG, "++ ON START ++");
		// Initialize the BluetoothReceiverService to perform bluetooth
		// connections
		ensureDiscoverable();
//		mReceiverService = new RemoteControlReceiver(this, mHandler);

		// Al iniciar la actividad se muestra la primera imagen.
		if (D)
			Log.e(TAG, "++ PRIMERA IMAGEN ++");
		// g.setSelection(posicionImagen);
	}

	@Override
	public synchronized void onResume() {
		super.onResume();
		if (D)
			Log.e(TAG, "+ ON RESUME +");

//		mReceiverService.start();
	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();
		if (D)
			Log.e(TAG, "onDestroy");
		estado = 0;
		if (null != mT) {
			mT.funcionaHilo = false;
			mT.cancel();
		}

		if (D)
			Log.e(TAG, "Thread cancel");
		mT = null;
	}

	private void ensureDiscoverable() {
		if (D)
			Log.e(TAG, "ensure discoverable");
		if (mAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
		}
	}

	private class HiloEscuchador extends Thread {
		BluetoothSocket socket = null;
		private boolean funcionaHilo = true;

		public void cancel() {
			if (D)
				Log.d(TAG, "cancel " + this);
			try {
				funcionaHilo = false; // Para finalizar el hilo
				mmServerSocket.close();
			} catch (IOException e) {
				Log.e(TAG, "close() of server failed", e);
			}
		}

		@Override
		public void run() {
			if (D)
				Log.e(TAG, "Thread_" + "run");
			try {
				mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord(
						NAME, MY_UUID);
				if (D)
					Log.e(TAG, "serverSocket");
			} catch (IOException e) {
				Log.e(TAG, "listen() failed", e);
				return;
			}

			try {
				if (D)
					Log.e(TAG, "Esperando en accept ...");
				socket = mmServerSocket.accept();

				if (D)
					Log.e(TAG, "accept");
			} catch (IOException e) {
				Log.e(TAG, "accept failed");
				return;
			}

			if (D)
				Log.e(TAG, " getInputStream");

			try {
				mmInStream = socket.getInputStream();
				if (D)
					Log.e(TAG, "getInputStream - OK");
			} catch (IOException e) {
				Log.e(TAG, "temp sockets not created", e);
				return;
			}

			int bytes;
			byte[] buffer = new byte[1024];
			while (funcionaHilo) {
				try {
					if (D)
						Log.e(TAG, "Vamos a leer ...");
					bytes = mmInStream.read(buffer);
					if (D)
						Log.e(TAG, "Hemos leido!!!!" + bytes + " "
								+ new Integer(new String(buffer, 0, bytes)));

					int iComando = new Integer(new String(buffer, 0, bytes))
							.intValue();
					mHandler.obtainMessage(Receiver.MESSAGE_READ, iComando, -1)
							.sendToTarget();
				} catch (IOException e) {
					Log.e(TAG, "disconnected", e);
					funcionaHilo = false;
					break;
				}
			}

		}
	}

	// The Handler that gets information back from the BluetoothReceiverService
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (D) {
				Log.e(TAG, "Se ejecuta el handleMessage.");
			}

			switch (msg.what) {
			// case MESSAGE_STATE_CHANGE:
			// case BluetoothReceiverService.STATE_CONNECTED:
			// case BluetoothReceiverService.STATE_CONNECTING:
			// case BluetoothReceiverService.STATE_LISTEN:
			// case BluetoothReceiverService.STATE_NONE:
			// case MESSAGE_WRITE:
			case MESSAGE_READ:
				if (D) {
					Log.e(TAG,
							"Se ejecuta el caso MESSAGE_READ que tiene arg1= "
									+ msg.arg1 + " arg2 = " + msg.arg2);
				}

				int readMessage = Integer.parseInt(String.valueOf(msg.arg1));
				if (readMessage == getResources().getInteger(
						R.integer.COMANDO_SIGUIENTE)) {

					// Restamos 1 porque el array de im�genes empieza en 0.
					if (posicionImagen == (numeroImagenesTotales - 1)) {
						Toast.makeText(Receiver.this, 
								"Fin de la presentaci�n.", Toast.LENGTH_SHORT)
								.show();
					} else {
						posicionImagen = posicionImagen + 1;
						g.setSelection(posicionImagen);
					}
				} else if (readMessage == getResources().getInteger(
						R.integer.COMANDO_ANTERIOR)) {

					if (0 == posicionImagen) {
						Toast.makeText(Receiver.this,getResources().getString(R.string.firstImage),
								Toast.LENGTH_SHORT).show();
					} else {
						posicionImagen = posicionImagen - 1;
						g.setSelection(posicionImagen);
					}
				} else if (readMessage == getResources().getInteger(
						R.integer.COMANDO_PRIMERO)) {
					if (0 == posicionImagen) {
						Toast.makeText(Receiver.this, getResources().getString(R.string.firstImage),
								Toast.LENGTH_SHORT).show();
					} else {
					posicionImagen = 0;
					g.setSelection(posicionImagen);
					}
				} else if (readMessage == getResources().getInteger(
						R.integer.COMANDO_ULTIMO)) {
					if (posicionImagen == (numeroImagenesTotales - 1)) {
						Toast.makeText(Receiver.this, getResources().getString(R.string.lastImage), 
										Toast.LENGTH_SHORT).show();
					} else {
					posicionImagen = numeroImagenesTotales - 1;
					g.setSelection(posicionImagen);
					}
				} else if (readMessage == getResources().getInteger(
						R.integer.COMANDO_PLAY)) {
					
					
					
					
					Thread hiloG = new Thread() {
						public void run() {
					Animation animation = AnimationUtils.loadAnimation(Receiver.this,R.anim.custom_anim);

					        animation.getInterpolator();
					        animation.setDuration(1000);
					        animation.setStartOffset(200);
					        animation.setRepeatMode(2);
//					        animation.setFillAfter(false);
//					        animation.setFillEnabled(true);
//					        g.setSelection(0);
					        animation.setFillAfter(false);
					        animation.setFillEnabled(true);
//
//					        
//					        g.setAnimation(animation);
//					        g.startAnimation(animation);
					
					int i = 0;
					Log.e(TAG, "Empiezo " + i);
					while (!PARAR_GALERIA && i <(numeroImagenesTotales)) {
						if (i < (numeroImagenesTotales)) {
							Log.e(TAG, "setSelection " + i);
							g.setSelection(i);
							i++;
					        g.setAnimation(animation);
					        g.startAnimation(animation);
					      
					      
//							try {
//								Log.e(TAG, "Durmiendo " + i);
//								Thread.sleep(2000);
//							} catch (InterruptedException ie) {
//								Log.e(TAG, ie.toString());
//							}
						} else {
							Log.e(TAG, "Else " + i);
						}
					}
					}//run()
					};
					hiloG.start();
					
				} else if (readMessage == getResources().getInteger(
						R.integer.COMANDO_STOP)) {
					g.clearAnimation();
				}
			default:
				Log.e(TAG, "Se ejecuta el caso por defecto con valor = "
						+ msg.what);
				break;
			}

		}
	};

	public void onActivityResult(int requestCode, int resultCode, Intent i) {
		if (D)
			Log.d(TAG, "onActivityResult ");
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			if (Activity.RESULT_OK == resultCode) {
				if (D) {
					Log.e(TAG, "ENABLE_BT OK");
				}

				// Initialize the BluetoothReceiverService to perform bluetooth
				// connections
//				mReceiverService = new RemoteControlReceiver(this, mHandler);
			} else {
				if (D)
					Log.e(TAG, "ENABLE_BT OK");
				finish();
			}
			break;
		}
	}

	public class ImageAdapter extends BaseAdapter {

		int mGalleryItemBackground;
		private Context mContext;

		// private Integer[] mImageIds = {
		// R.drawable.and1,
		// R.drawable.and2,
		// R.drawable.and3,
		// R.drawable.and4,
		// R.drawable.and5,
		// R.drawable.and6
		// };

		public ImageAdapter(Context c) {
			mContext = c;

		}

		public int getCount() {
			return mUrls.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);
			Log.e(TAG, "++ imageAdaptergetView ++");
			i.setImageURI(mUrls[position]);
//			i.setScaleType(ImageView.ScaleType.FIT_XY);
			i.setLayoutParams(new Gallery.LayoutParams(260, 210));
			imgView.setImageURI(mUrls[position]);
			return i;
		}
	}

	public boolean comprobarSD() {
		boolean mExternalStorageAvailable = false;
		Log.e(TAG, "++ comprobarSD ++");
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageAvailable = true;
			Log.e(TAG, "++ SDTrue ++");
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			Log.e(TAG, "++ SDTrue ++");
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = false;
			Log.e(TAG, "++ SDFalse ++");
		}
		return mExternalStorageAvailable;
	}
}
